const express = require('express');
const router = express.Router();
const EventService = require('../services/eventService');

// 获取所有事件
router.get('/', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    // 获取事件总数
    const db = require('../db/database');
    const total = await new Promise((resolve) => {
      db.get("SELECT COUNT(*) as count FROM events", (err, row) => {
        resolve(row ? row.count : 0);
      });
    });
    
    // 获取事件列表
    const Event = require('../models/Event');
    const events = await Event.getAll(page, limit);
    
    res.json({
      success: true,
      data: events,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取事件列表失败:', error);
    res.status(500).json({
      success: false,
      error: '获取事件列表失败'
    });
  }
});

// 获取单个事件详情
router.get('/:id', async (req, res) => {
  try {
    const event = await EventService.getEventDetails(req.params.id);
    res.json({
      success: true,
      data: event
    });
  } catch (error) {
    console.error('获取事件详情失败:', error);
    res.status(404).json({
      success: false,
      error: error.message || '事件不存在'
    });
  }
});

// 创建新事件
router.post('/', async (req, res) => {
  try {
    const { title, description, severity } = req.body;
    
    if (!title || !severity) {
      return res.status(400).json({
        success: false,
        error: '标题和严重性不能为空'
      });
    }
    
    const event = await EventService.createEvent(title, description, severity);
    
    res.status(201).json({
      success: true,
      message: '事件创建成功',
      data: event
    });
  } catch (error) {
    console.error('创建事件失败:', error);
    res.status(500).json({
      success: false,
      error: error.message || '创建事件失败'
    });
  }
});

// 确认事件
router.post('/:id/acknowledge', async (req, res) => {
  try {
    const { userId } = req.body;
    
    if (!userId) {
      return res.status(400).json({
        success: false,
        error: '用户ID不能为空'
      });
    }
    
    const event = await EventService.acknowledgeEvent(req.params.id, userId);
    
    res.json({
      success: true,
      message: '事件已确认',
      data: event
    });
  } catch (error) {
    console.error('确认事件失败:', error);
    res.status(400).json({
      success: false,
      error: error.message || '确认事件失败'
    });
  }
});

// 解决事件
router.post('/:id/resolve', async (req, res) => {
  try {
    const { userId } = req.body;
    
    if (!userId) {
      return res.status(400).json({
        success: false,
        error: '用户ID不能为空'
      });
    }
    
    const event = await EventService.resolveEvent(req.params.id, userId);
    
    res.json({
      success: true,
      message: '事件已解决',
      data: event
    });
  } catch (error) {
    console.error('解决事件失败:', error);
    res.status(400).json({
      success: false,
      error: error.message || '解决事件失败'
    });
  }
});

// 获取待处理事件
router.get('/status/pending', async (req, res) => {
  try {
    const events = await EventService.getPendingEvents();
    res.json({
      success: true,
      data: events
    });
  } catch (error) {
    console.error('获取待处理事件失败:', error);
    res.status(500).json({
      success: false,
      error: '获取待处理事件失败'
    });
  }
});

module.exports = router;